package com.java2404.micro.consumer.handler;

import com.java2404.micro.common.entity.User;
import com.java2404.micro.consumer.client.GatewayClient;
import com.java2404.micro.consumer.service.ConsumerService;
import com.java2404.micro.common.entity.Order;
import com.java2404.micro.common.resp.Result;
import com.java2404.micro.consumer.service.UserService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private GatewayClient gatewayClient; // 使用 OpenFeign 调用微服务

    @Autowired
    private UserService userService;

    /**
     * 根据用户 ID 查询用户信息
     * @param userId 用户 ID
     * @return 用户信息
     */
    @GetMapping("/getUserById")
    public Result<User> getUserById(@RequestParam("userId") Integer userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }



    /**
     * 用户下单接口
     * @param userId 用户ID
     * @param gid 商品ID
     * @param amount 购买数量
     * @param price 商品单价
     * @return Result
     */
    @GetMapping("/createOrder")
    @GlobalTransactional(name = "create-order-tx", rollbackFor = Exception.class)
    public Result createOrder(@RequestParam("userId") Integer userId,
                              @RequestParam("gid") Integer gid,
                              @RequestParam("amount") Integer amount,
                              @RequestParam("price") BigDecimal price) {
        // 1. 计算总金额
        BigDecimal totalPrice = price.multiply(new BigDecimal(amount));

        // 2. 获取商品名称（通过商品微服务获取，确保名称准确）
        Result<String> goodsResult = gatewayClient.getGoodsName(gid);
        if (goodsResult.getCode()==0) {
            throw new RuntimeException("获取商品名称失败");
        }
        String goodsName = goodsResult.getData();

        // 3. 检查库存是否足够
        Result<Boolean> stockResult = gatewayClient.checkStock(gid, amount);
        if (stockResult.getCode()==0 || !stockResult.getData()) {
            return Result.error("库存不足，无法下单");
        }

        // 4. 创建订单
        Order order = new Order();
        order.setUid(userId);
        order.setGid(gid);
        order.setGname(goodsName);
        order.setGprice(totalPrice);
        order.setGstatus(0);  // 已下单
        order.setCreate_time(LocalDateTime.now());
        order.setUpdate_time(LocalDateTime.now());
        order.setCreate_by("系统");

        Result orderResult = gatewayClient.addOrder(order);
        if (orderResult.getCode()==0) {
            throw new RuntimeException("订单创建失败");
        }

        // 5. 扣减库存
        Result<Boolean> deductStockResult = gatewayClient.deductStock(gid, amount);
        if (deductStockResult.getCode() == 0 || !deductStockResult.getData()) {
            return Result.error("库存扣减失败");
        }

        return Result.success("订单创建成功，请尽快支付");
    }
}
